package service.impl.v2;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import dao.v2.ApplyReturnVOMapper;
import dao.v2.ConfigVOMapper;
import dao.v2.MemberCartVOMapper;
import dao.v2.OrderVOMapper;
import dao.v2.UorderBackVOMapper;
import dao.v2.UorderVOMapper;
import factory.DistributionLock;
import factory.RedisDistributionLock;
import model.FileVO;
import model.LogOrderBack;
import model.MemberVO;
import model.OrderBackItemVO;
import model.OrderBackVO;
import model.OrderTimer;
import model.OrderVO;
import model.SeqVO;
import model.UorderGoodVO;
import model.UorderVO;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import service.v2.UorderBackService;
import util.PropertieUtil;

@Service
public class UorderBackServiceImpl implements UorderBackService{
	
	@Autowired
	private UorderBackVOMapper dao;
	
	@Autowired
	private UorderVOMapper uorderVOMapper;
	
	@Autowired
	private OrderVOMapper orderVOMapper;
	
	@Autowired
	private ApplyReturnVOMapper applyReturnVOMapper;
	
	@Autowired
	private ConfigVOMapper configVOMapper;
	
	@Autowired
	private MemberCartVOMapper memberCartVOMapper;
	
	@Autowired
	@Qualifier("lockRedisTemplate")
	private RedisTemplate<Object, Object> lockRedisTemplate;
	
	
	public static  Object  a = new Object();
	
	
	public List<UorderVO> getUorderBackList(UorderVO ordervo) {
		return dao.getUorderBackList(ordervo);
	}

	public int getTotal(UorderVO ordervo) {
		return dao.getTotal(ordervo);
	}
	
	
	/**
	 * 提货退货申请处理
	 * @throws Exception 
	 */
	public  String subOrderBack(MemberVO member, String data, String order_id, String case_id, String address_name, String address_tel,String country) throws Exception {
	
		//修改包裹状态
		uorderVOMapper.updOrderCaseState(case_id,"4","7");
		// data 数据
		JSONArray jsonArray = JSONArray.fromObject(data);
		String order_back_id  = "";
		
		//计算退款总金额
		double back_price = 0;
		double price = 0;
		List<String> good_id_list = new ArrayList<String>();
		JSONObject obj = null;
		for (int i = 0; i < jsonArray.size(); i++) {
			obj = (JSONObject)jsonArray.get(i);
			price = orderVOMapper.getBackPrice(obj.get("order_good_id").toString(),obj.get("num").toString());
			back_price = back_price + price;
			good_id_list.add(obj.get("order_good_id").toString());
		}
		
		//提交退货申请(包裹) 故 停止7天自动收货时间定时器 
		dao.stopCaseTimerWhenBack(order_id,case_id);

		OrderVO order = orderVOMapper.getOrderById(order_id);
		OrderBackVO orderBack = new OrderBackVO();
		orderBack.setOrder_id(order_id);
		orderBack.setCase_id(case_id);
		orderBack.setState("0");
		orderBack.setName(address_name);
		orderBack.setTel(address_tel);
		orderBack.setTotal_price(String.valueOf(Double.parseDouble(order.getTotal_price())+Double.parseDouble(order.getFreight())));
		orderBack.setBack_price(String.valueOf(back_price));
		
		DistributionLock lock = new RedisDistributionLock(lockRedisTemplate,"subOrderBack"+member.getId());
		lock.acquire();
		int checkCount = dao.checkOrderBack(good_id_list,order_id);
		if(checkCount>0){
			return "";
		}else{
			//存入 order back 
			applyReturnVOMapper.InsertOrderBack(orderBack);
			order_back_id  = orderBack.getId();
			JSONObject json = null;
			JSONArray fileList = null;
			String folder_id = null;
			for (int i = 0; i < jsonArray.size(); i++) {
				json = (JSONObject) jsonArray.get(i);
				fileList = (JSONArray) json.get("file");
				SeqVO seq = new SeqVO();
				applyReturnVOMapper.getSeq(seq);
				folder_id = seq.getSeq();
				
				FileVO fileVO = new FileVO();
				for (int j = 0; j < fileList.size(); j++) {
					fileVO.setCat_id(PropertieUtil.loadPropertie("order_back_img"));
					fileVO.setPath(fileList.get(j).toString());
					fileVO.setFolder_id(folder_id);
					applyReturnVOMapper.addFile(fileVO);
				}
				
			
				OrderBackItemVO orderBackItem = new OrderBackItemVO();
				orderBackItem.setOrder_back_id(order_back_id);
				orderBackItem.setOrder_good_id(json.get("order_good_id").toString());
				orderBackItem.setNum(json.get("num").toString());
				orderBackItem.setState("0");
				orderBackItem.setReason(json.get("reason").toString());
				orderBackItem.setRemark(json.get("detail").toString());
				orderBackItem.setFold_id(folder_id);
				//存入 order back item
				applyReturnVOMapper.InsertOrderBackItem(orderBackItem);
			}
			
			LogOrderBack logOrderBack = new LogOrderBack();
			logOrderBack.setOrder_back_id(order_back_id);
			logOrderBack.setMember_id(member.getId());
			if("0".equals(country)){	
				logOrderBack.setRemark("Your application has been submit, please wait for process, it usually take 1-2 working days.");
			}else{
				logOrderBack.setRemark("退货申请已提交，等待客服受理，通常需要1-2个工作日");	
			}
			logOrderBack.setType("0");
			logOrderBack.setCase_id(case_id);
			applyReturnVOMapper.addLogOrderBack(logOrderBack);
		}
		lock.release();
		return  order_back_id;
	}

	/**
	 * 用户取消 退货申请(食了粪！)
	 */
	public void revokeOrderBack(String order_id, String order_back_id,String case_id,String member_id,String country) {
		//修改退货单状态 
		int count  = applyReturnVOMapper.updOrderBackState(order_back_id,"4");
		if(count>0){
			LogOrderBack log = new LogOrderBack();
			log.setOrder_back_id(order_back_id);
			log.setMember_id(member_id);
			if("0".equals(country)){
				log.setRemark("Cancel Application.");
			}else{
				log.setRemark("取消申请");	
			}
			log.setType("0");
			applyReturnVOMapper.addLogOrderBack(log);
			
			//从来开始收7天获定时器
			int updCount = dao.getBackProcessCount(order_back_id);
			
			if(updCount==0){
				int updCaseCount = uorderVOMapper.updOrderCaseState(case_id, "7", "4");
				if(updCaseCount>0){
					dao.startTimer(order_id,case_id);
				}
			}
		}
	}

	public List<UorderGoodVO> getBackOrderDetails(String case_id) {
		return dao.getBackOrderDetails(case_id);
	}

	public void sendBackGoods(String member_id,OrderBackVO order_back, String ems_id, String ems_no,String country) {
		String user_back_time  = configVOMapper.loadConfig("USER_BACK_TIME");
		
		LogOrderBack log = new LogOrderBack();
		log.setOrder_back_id(order_back.getId());
		log.setMember_id(member_id);
		if("0".equals(country)){
			log.setRemark("Express information has been submit, service staff will process the refund after they receive the product.");
		}else{
			log.setRemark("物流信息已提交，客服会在收到商品后处理退款");	
		}
		log.setType("4");
		applyReturnVOMapper.addLogOrderBack(log);
		
		OrderTimer orderTime = new OrderTimer();
		orderTime.setOrder_id(order_back.getOrder_id());
		orderTime.setCase_id(order_back.getCase_id());
		orderTime.setOpen_yn("Y");
		orderTime.setType("2");
		orderTime.setTime(user_back_time);
		orderTime.setOrder_back_id(order_back.getId());
		memberCartVOMapper.addOrderTimer(orderTime);
		
		applyReturnVOMapper.updOrderBackEms(order_back.getId(),ems_id,ems_no);
		
	}

	public OrderBackVO getorderbackById(String order_back_id) {
		return dao.getorderbackById(order_back_id);
	}

	public UorderVO getOrderAddressByCaseId(String case_id) {
		return dao.getOrderAddressByCaseId(case_id);
	}
	
}
